package com.tuo51.manager.controller;


import com.tuo51.evaluate.domain.evaluatingV2.EvaluateV2Dimension;
import com.tuo51.evaluate.repositories.evaluatev2.EvaluateV2DimensionRepository;
import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.manager.vo.EvaluateV2DimensionVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("/mapi/pbe_dimension")
@Api(value = "/mapi/pbe_dimension", tags = "OP - 儿心量表内容管理 - 能区")
public class MAPIPbEvaluateDimensionController {

    @Autowired
    EvaluateV2DimensionRepository itemRepository;

    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "资源列表")
    public StatusResponse list(@RequestHeader(TICKET) String ticket){

        cache.getStaffId(ticket);

        List<EvaluateV2DimensionVO> ret = itemRepository.findAllByDeletedOrderByCode(false).stream().map(k->EvaluateV2DimensionVO.of(k)).collect(Collectors.toList());

        return StatusResponse.success(ret);
    }

    @RequestMapping(value = "/info", method = GET)
    @ApiOperation(value = "内容详情")
    public StatusResponse info(@RequestHeader(TICKET) String ticket,
                               String itemId){

        cache.getStaffId(ticket);

        return StatusResponse.success(itemRepository.getOne(itemId));
    }

    @RequestMapping(value = "/edit", method = POST)
    @ApiOperation(value = "编辑")
    public StatusResponse edit(@RequestHeader(TICKET) String ticket,
                               EvaluateV2DimensionVO item){

        cache.getStaffId(ticket);

        EvaluateV2Dimension ret = null;
        if (StringUtils.isNotEmpty(item.getId())){
            ret = itemRepository.getOne(item.getId());
        }

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        BeanUtils.copyProperties(item, ret, new String[]{"deleted","id"});

        itemRepository.save(ret);

        return StatusResponse.success(ret);
    }

}
